package com.sx.pipeline.ui.service.add

import android.Manifest
import android.graphics.BitmapFactory
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.permissionx.guolindev.PermissionX
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.CustomCommonPicket
import com.sx.pipeline.custom.dialog.MyCityPickerListener
import com.sx.pipeline.custom.dialog.MyCityPickerPopup
import com.sx.pipeline.databinding.ActServiceAddBinding
import com.sx.pipeline.repos.http.res.ProvincesVO
import com.sx.pipeline.ui.service.ServiceVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CompressHelper
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.PermissionHelper


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 添加服务
 */
@Route(path = RoutePath.Service.SERVICE_ADD)
class ServiceAddActivity : CYDataBindingBaseActivity<ActServiceAddBinding, ServiceVM>
    (R.layout.act_service_add), View.OnClickListener {

    @JvmField
    @Autowired(name = IntentKey.ID)
    var deviceId: Int? = 0

    @JvmField
    @Autowired(name = IntentKey.TYPE)
    var type: Int? = 1  //1 添加设备  2编辑设备

    private var titleId: Int? = 0 //服务标题id

    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        //设置添加单位/联系人/手机号
        mBinding.sbUnitname.rightText = mViewModel.mModel.getUserData()?.unitName
        mBinding.etContact.setText(mViewModel.mModel.getUserData()?.userName)
        mBinding.etContactPhone.setText(mViewModel.mModel.getUserData()?.phone)

        //获取服务标题
        mViewModel.getServiceTitle()
        //获取联系人
        mViewModel.getContacts()
        when (type) {
            1 -> {
                mBinding.titleBar.title = getString(R.string.txt_service_add)
            }
            else -> {
                mBinding.titleBar.title = getString(R.string.txt_service_edit)
                mBinding.tvDelete.visibility = View.VISIBLE
                deviceId?.let { mViewModel.getServiceDeviceDetail(it) }
            }
        }
        initProductImages()

    }

    override fun initViewObservable() {
        super.initViewObservable()
        //加载服务标题数据
        observe(mViewModel.serviceTitleListEvent) {

        }

        //上传的图片
        observe(mViewModel.uploadDataEvent) {
            mBinding.imageProduct.addImage(it)
        }

        //编辑设备 设备数据
        observe(mViewModel.deviceDetailDataEvent) {
            titleId=it?.titleId
            deviceId=it?.id
            mViewModel.provinceIDField.set(it?.provinceId)
            mViewModel.cityIDField.set(it?.cityId)
            mViewModel.areaIDField.set(it?.areaId)
            mBinding.sbTitle.rightText=it?.title
            mBinding.etDesc.setText(it?.serverDescribe)
            mBinding.etPrice.setText(it?.price)
            mBinding.sbArea.rightText=it?.addressDetail
            mBinding.etContact.setText(it?.contact)
            mBinding.etContactPhone.setText(it?.contactPhone)
            it?.let {
                if (!TextUtils.isEmpty(it.images)) {
                    val imageList = it.images.split(",")
                    for (i in imageList) {
                        mBinding.imageProduct.addImage(i)
                    }
                }
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_principal -> {
                if (mViewModel.taskContactData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_principal))
                popup.setPickerData(mViewModel.taskContactData)
                popup.setCommonPickerListener { position, data ->
                    mBinding.etContact.setText(data)
                    mBinding.etContactPhone.setText(mViewModel.taskContactPhoneData[position])
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            R.id.sb_title -> {
                if (mViewModel.serviceTitleData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_service_title))
                popup.setPickerData(mViewModel.serviceTitleData)
                popup.setCommonPickerListener { index, data ->
                    mBinding.sbTitle.rightText = data
                    titleId = mViewModel.serviceTitleListEvent.value?.get(index)?.id
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            R.id.sb_area -> showProvincesDialog()
            R.id.tv_submit -> {
                if (type == 1) {
                    if (titleId==0) {
                        ToastUtils.showShort("请选择标题")
                        return
                    }
                    //添加设备
                    titleId?.let {
                        mViewModel.addServiceDevice(
                            it,
                            mBinding.sbTitle.rightText.toString(),
                            mBinding.etPrice.text.toString(),
                            mBinding.etDesc.text.toString(),
                            mBinding.sbArea.rightText.toString(),
                            mBinding.etContact.text.toString(),
                            mBinding.etContactPhone.text.toString(),
                            AndroidUtil.listToString(mBinding.imageProduct.imagePath).toString()
                        )
                    }
                } else {
                    if (titleId==0) {
                        ToastUtils.showShort("请选择标题")
                        return
                    }
                    //编辑设备
                    titleId?.let {
                        deviceId?.let { it1 ->
                            mViewModel.editServiceDevice(
                                it1,
                                it,
                                mBinding.sbTitle.rightText.toString(),
                                mBinding.etPrice.text.toString(),
                                mBinding.etDesc.text.toString(),
                                mBinding.sbArea.rightText.toString(),
                                mBinding.etContact.text.toString(),
                                mBinding.etContactPhone.text.toString(),
                                AndroidUtil.listToString(mBinding.imageProduct.imagePath).toString()
                            )
                        }
                    }
                }

            }
            R.id.tv_delete -> {
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .asConfirm(
                        getString(R.string.hint), getString(R.string.txt_confirm_delete_device),
                        getString(R.string.cancel), getString(R.string.confirm),
                        {
                            //请求删除设备
                            deviceId?.let { mViewModel.getServiceDelete(it) }
                        }, null, false
                    ).show()
            }
        }
    }


    //设备图片
    private fun initProductImages() {
        // 上传图片
        mBinding.imageProduct.initAdapter(3, 3)
        mBinding.imageProduct.setImageUploadListener {
            PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :
                PermissionUtils.SimpleCallback{
                override fun onGranted() {
                    PictureSelector.create(this@ServiceAddActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(3 - mBinding.imageProduct.imagePath.size)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                //循环上传图片
                                for (i in 0 until result?.size!!) {
                                    Log.d("okhttp", "" + result[i]?.realPath)
                                    //压缩图片
                                    val inputBitmap =
                                        BitmapFactory.decodeFile(result[i]?.realPath)
                                    val compressFile = CompressHelper.compressQuality(
                                        this@ServiceAddActivity,
                                        inputBitmap
                                    )
                                    mViewModel.uploadImage(compressFile)
                                }
                            }

                            override fun onCancel() {}
                        })
                }

                override fun onDenied() {
                    ToastUtils.showShort("请授权后再继续操作")
                }
            },Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)

//            PermissionX.init(this)
//                .permissions(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA
//                )
//                .onExplainRequestReason { scope, deniedList ->
//                    scope.showRequestReasonDialog(
//                        deniedList,
//                        "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                        "确认",
//                        "取消"
//                    )
//                }
//                .onForwardToSettings { scope, deniedList ->
//                    scope.showForwardToSettingsDialog(
//                        deniedList,
//                        "您需要手动在“设置”中允许必要的权限",
//                        "确定",
//                        "取消"
//                    )
//                }
//                .request { allGranted, grantedList, deniedList ->
//                    if (allGranted) {
//                        PictureSelector.create(this)
//                            .openGallery(SelectMimeType.ofImage())
//                            .setImageEngine(GlideEngine.createGlideEngine())
//                            .setMaxSelectNum(3 - mBinding.imageProduct.imagePath.size)
//                            .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                                override fun onResult(result: ArrayList<LocalMedia?>?) {
//                                    //循环上传图片
//                                    for (i in 0 until result?.size!!) {
//                                        Log.d("okhttp", "" + result[i]?.realPath)
//                                        //压缩图片
//                                        val inputBitmap =
//                                            BitmapFactory.decodeFile(result[i]?.realPath)
//                                        val compressFile = CompressHelper.compressQuality(
//                                            this@ServiceAddActivity,
//                                            inputBitmap
//                                        )
//                                        mViewModel.uploadImage(compressFile)
//                                    }
//                                }
//
//                                override fun onCancel() {}
//                            })
//                    } else {
//                        ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                    }
//                }

        }
    }


    /**
     * 省市区选择
     */
    private fun showProvincesDialog() {
        val popup = MyCityPickerPopup(ActivityUtils.getTopActivity())
        popup.setCityPickerListener(object : MyCityPickerListener {
            override fun onCityConfirm(
                provincesVO: ProvincesVO?, cityVO: ProvincesVO?, areaVO: ProvincesVO?,
                province: String?, city: String?, area: String?, v: View?,
            ) {
                mViewModel.provinceIDField.set(provincesVO!!.id.toInt())
                mViewModel.cityIDField.set(cityVO!!.id.toInt())
                mViewModel.areaIDField.set(areaVO!!.id.toInt())
                mViewModel.addressField.set("$province $city $area")
                mViewModel.longitudeField.set(areaVO.center.split(",")[0])
                mViewModel.latitudeField.set(areaVO.center.split(",")[1])
                // 显示地址
                mBinding.sbArea.rightText = "$province $city $area"
            }

            override fun onCityChange(province: String?, city: String?, area: String?) {

            }
        })
        XPopup.Builder(this).asCustom(popup).show()
    }
}